<template>
  <el-dialog :title="title" :visible.sync="visible" width="500px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入编码" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="权重" prop="rate">
        <el-input v-model="form.rate" placeholder="请输入权重" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveRelation } from '@/api/project/user-relation'

export default {
  name: 'UserRelationModal',
  data() {
    const rateValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入权重'))
      }
      if (value < 0.0 || value > 1.0) {
        callback(new Error('请输入0.0-1.0之间的数值'))
      }
      callback()
    }
    return {
      title: '人事关系配置',
      buttonLoading: false,
      visible: false,
      form: {
        formKey: ''
      },
      rules: {
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        rate: [
          {
            validator: rateValidator,
            trigger: 'blur',
            required: true
          }
        ]
      }
    }
  },
  methods: {
    reset() {
      this.resetForm('form')
      this.buttonLoading = false
      this.form = {}
    },
    add() {
      this.reset()
      this.visible = true
    },
    update() {
      this.visible = true
    },
    submitForm() {
      const _this = this
      this.buttonLoading = true
      console.log(this.form)
      this.$refs.form.validate((valid) => {
        if (valid) {
          saveRelation(this.form)
            .then((res) => {
              console.log(res)
              if (res.code == 200) {
                this.$message.success('保存成功~')
              } else {
                this.$message.error('保存失败~')
              }
            })
            .finally((res) => {
              _this.buttonLoading = false
              _this.visible = false
              _this.$emit('ok')
            })
        } else {
          console.log('submit error')
          return
        }
      })
    },
    cancel() {
      this.visible = false
      this.$emit('ok')
    }
  }
}
</script>

<style scoped></style>
